package com.yxt.admin.controller;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.yxt.admin.config.ResourceServerConfig;
import com.yxt.admin.entity.SysConfig;
import com.yxt.admin.entity.SysRole;
import com.yxt.admin.entity.SysUser;
import com.yxt.admin.entity.UserEntity;
import com.yxt.admin.enums.UserStatus;
import com.yxt.admin.service.ISysPostService;
import com.yxt.admin.service.ISysRoleService;
import com.yxt.admin.service.ISysUserService;
import com.yxt.admin.dto.UserDto;
import com.yxt.admin.service.impl.SysPermissionService;
import com.yxt.admin.utils.SecurityUtils;
import com.yxt.common.annotation.Log;
import com.yxt.common.constant.Constant;
import com.yxt.common.enums.BusinessType;
import com.yxt.common.exception.BaseException;
import com.yxt.common.utils.StringUtils;
import com.yxt.common.utils.ajax.PageUtils;
import com.yxt.common.utils.ajax.R;
import com.yxt.common.utils.redis.RedisCache;
import com.yxt.common.utils.sign.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


/**
 * 系统用户
 *
 * @author august
 * @email 379249906@qq.com
 * @date 2020-07-31 17:49:40
 */
@RestController
@Slf4j
@RequestMapping("/admin/user")
public class UserController {
//    @Autowired
//    private UserService userService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private PasswordEncoder passwordEncoder;
    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params,SysUser sysUser){
        PageUtils page = userService.queryPage(params,sysUser);
//        return R.ok().put("page", page);
        return R.ok().put("data", page);
    }

//    @PreAuthorize("@ss.hasPermi('system:user:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(SysUser user)
//    {
//        startPage();
//        List<SysUser> list = userService.selectUserList(user);
//        TableDataInfo dataTable = getDataTable(list);
//        return dataTable;
//    }

    @GetMapping("/hello")
    public String hello(){
        return "hellouser";
    }

    @GetMapping("/hello2")
    public String hello2(){
        return "hellouser";
    }
    /**
     * 信息
     */
    @RequestMapping("/info/{userId}")
    public R info(@PathVariable("userId") Long userId){
//		UserEntity user = userService.getById(userId);
//
//        return R.ok().put("user", user);
        return R.ok();
    }

    @GetMapping("/info")
    public UserDto findByUserName(@RequestParam("userName")String username) {
        System.out.println("1111:1111:11111");
        SysUser user = userService.selectUserByUserName(username);

        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }

//        LambdaQueryWrapper<UserEntity> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        userLambdaQueryWrapper.eq(userName!=null,UserEntity::getUsername,userName);
//        UserEntity userEntity = userService.getOne(userLambdaQueryWrapper);
//        UserDto userDto = new UserDto();
//        userDto.setPassword(userEntity.getPassword());
//        userDto.setUsername(userName);
//        return userDto;
      //  return createLoginUser(user);
        UserDto loginUser = createLoginUser(user);
        return loginUser;
    }

    public UserDto createLoginUser(SysUser user)
    {
        return new UserDto(user, permissionService.getMenuPermission(user));
    }

    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping(value = { "/", "/{userId}" })
    @JsonInclude(JsonInclude.Include.ALWAYS)
    public R getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {

        R ok = R.ok();
        List<SysRole> roles = roleService.selectRoleAll();

        ok.put("roles",SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()))
                .put("posts", postService.selectPostAll());

        if (StringUtils.isNotNull(userId))
        {
            ok.put("data", userService.selectUserById(userId));
            ok.put("postIds", postService.selectPostListByUserId(userId));
            ok.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ok;
    }

    /**
     * 新增用户
     */
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysUser user)
    {
        if (Constant.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return R.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (Constant.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return R.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (Constant.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return R.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }

        OAuth2AuthenticationDetails authentication = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        Map<String, String> stringStringMap = JwtUtil.decodeToken(authentication.getTokenValue(), ResourceServerConfig.PUBLIC_KEY);
        String userId = String.valueOf(stringStringMap.get("userId"));
        UserDto userDto = redisCache.getCacheObject(Constant.USER_ACCOUNT_KEY+userId);

        user.setCreateBy(userDto.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));

        return userService.insertUser(user) > 0 ? R.ok() : R.error();

    }

    /**
     * 删除用户
     */
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public R remove(@PathVariable Long[] userIds)
    {
        return userService.deleteUserByIds(userIds) > 0 ? R.ok() : R.error();
    }

    /**
     * 修改用户
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        if (Constant.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return R.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (Constant.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return R.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }

        OAuth2AuthenticationDetails authentication = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        Map<String, String> stringStringMap = JwtUtil.decodeToken(authentication.getTokenValue(), ResourceServerConfig.PUBLIC_KEY);
        String userId = String.valueOf(stringStringMap.get("userId"));
        UserDto userDto = redisCache.getCacheObject(Constant.USER_ACCOUNT_KEY+userId);
        user.setUpdateBy(userDto.getUsername());

        return userService.updateUser(user) > 0 ? R.ok() : R.error();
    }

//    @GetMapping("/userInfo")
//    public R getUserInfo(){
////        OAuth2AuthenticationDetails authentication = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
////        Map<String, String> stringStringMap = JwtUtil.decodeToken(authentication.getTokenValue(), ResourceServerConfig.PUBLIC_KEY);
////
////        String userName = stringStringMap.get("user_name");
////
////
////        return R.ok().put("data",stringStringMap);
//       // return userService.getUserInfo();
//        return R.ok();
//    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody UserEntity user){
//        String encodePWD = passwordEncoder.encode(user.getPassword());
//        user.setPassword(encodePWD);
//        userService.save(user);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody UserEntity user){
//		userService.updateById(user);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] userIds){
		//userService.removeByIds(Arrays.asList(userIds));

        return R.ok();
    }

}
